package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class ZhihuRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;

    public Map<String, Object> handleRoute(boolean noCache) throws Exception {
        Map<String, Object> listResult = getList(noCache);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "zhihu");
        routeData.put("favicon", "https://www.zhihu.com/favicon.ico");
        routeData.put("title", "知乎");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "热榜");
        routeData.put("link", "https://www.zhihu.com/hot");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据到redis
        cacheDataInRedis.cacheData("zhihu:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index+1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private Map<String, Object> getList(boolean noCache) throws Exception {
        String url = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.body();

        JsonNode jsonNode = objectMapper.readTree(body);
        JsonNode dataNode = jsonNode.path("data");

        List<Map<String, Object>> list = new ArrayList<>();
        for (JsonNode itemNode : dataNode) {
            Map<String, Object> data = new LinkedHashMap<>();
            JsonNode targetNode = itemNode.path("target");

//            data.put("id", targetNode.path("id").asText());
            data.put("title", targetNode.path("title").asText());
//            data.put("desc", targetNode.path("excerpt").asText());
//            data.put("cover", itemNode.path("children").get(0).path("thumbnail").asText());
//            data.put("timestamp", getTime(targetNode.path("created").asLong()));
//            data.put("hot", Double.parseDouble(itemNode.path("detail_text").asText().split(" ")[0]) * 10000);
            data.put("url", "https://www.zhihu.com/question/" + targetNode.path("id").asText());
            data.put("mobileUrl", "https://www.zhihu.com/question/" + targetNode.path("id").asText());

            list.add(data);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("fromCache", false); // Modify based on your caching logic
        result.put("updateTime", System.currentTimeMillis());
        result.put("data", list);

        return result;
    }

    private String getTime(long timestamp) {
        // Implement this method to convert the timestamp into the desired format
        return String.valueOf(timestamp);
    }

    public Map<String, Object> getZhihuRanking() throws Exception {
        return handleRoute(false);
    }
}
